<?php

namespace Mini;

class Router
{
    protected static array $routes = [];

    public static function get(string $path, callable|array $handler): void
    {
        self::$routes['GET'][$path] = $handler;
    }

    public static function post(string $path, callable|array $handler): void
    {
        self::$routes['POST'][$path] = $handler;
    }

    public static function dispatch(): void
    {
        $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
        $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?: '/';

        foreach (self::$routes[$method] ?? [] as $route => $handler) {
            if ($route === $path) {
                if (is_array($handler)) {
                    [$class, $action] = $handler;
                    (new $class())->$action();
                } else {
                    $handler();
                }
                return;
            }
        }

        http_response_code(404);
        echo "404 Not Found";
    }
}
